<?php
namespace Api\Controller;

class UserController extends CommonController{
	
	//用户登录
	public function login(){
		$mobile   = $this->_post('mobile', '手机号不能为空！');
		$password = $this->_post('password', '密码不能为空！');

		//手机号判断
		if(preg_match('/^1[34578][0-9]{9}$/', $mobile) == false){
			$this->error('对不起，手机号不正确！');
		}

		//获取用户信息
		$where['mobile'] = $mobile;
		$info = D('User')->where($where)->find();
		$user_id = $info['user_id'];

		//判断密码
		$password_md5 = password_md5_one($user_id, $password);
		if($info['password'] != $password_md5){
			$this->error('您的用户名或者密码有误！');
		}
		//判断是否禁用
		if($info['status'] == 0){
			$this->error('您的账号被禁用，请联系相关人员！');
		}
		$user_id = $info['user_id'];

		//获取用户信息
		$user_info = D('User')->user_info($user_id);
		$user_info['token'] = D('User')->make_token($user_id);
		//积分处理
		D('UserScore')->role_update_score($user_id);
		
		$this->success('登录成功！',$user_info);
	}
	//用户注册
	public function register(){
		$mobile    = $this->_post('mobile', '手机号不能为空！');
		$email     = $this->_post('email', '');
		$password  = $this->_post('password', '密码不能为空！');
		$smscode   = $this->_post('smscode', '短信码不能为空！');
		$is_lawyer = $this->_post('is_lawyer', '', 0);
		$city_id   = $this->city_id();
		//手机号判断
		if(preg_match('/^1[34578][0-9]{9}$/', $mobile) == false){
			$this->error('对不起，手机号不正确！');
		}
		//判断手机号是否注册过
		if(D('User')->mobile_exists($mobile)){
			$this->error('对不起，手机号已存在！');
		}
		//验证码判断
		$cache_smscode = S('API_SMSCODE_' . $mobile);
		if($cache_smscode != $smscode){
			$this->error('对不起，验证码不正确！');
		}
		//清空验证码缓存
		S('API_SMSCODE_' . $mobile, null);
		//省份城市ID
		if($city_id){
			$data['city_id']     = $city_id;
			$data['province_id'] = D('Area')->get_parent_id($city_id);
		}

		//再次MD5加密
		$user_id = D('User')->generate_user_id();
		$data['user_id']     = $user_id;
		$data['mobile']      = $mobile;
		$data['is_lawyer']   = $is_lawyer;
		$data['password']    = password_md5_one($user_id, $password);
		$data['create_time'] = time();
		D('User')->add($data);

		//获取用户信息
		$user_info = D('User')->user_info($user_id);
		$user_info['token'] = D('User')->make_token($user_id);
		//积分处理
		D('UserScore')->role_update_score($user_id);

		$this->success('注册成功！',$user_info);
	}
	//修改密码
	public function edit_password(){
		$user_id     = $this->user_id();
		$newpassword = $this->_post('newpassword','新密码不能为空！');

		$user_model = D('User');

		$where['user_id'] = $user_id;
		$info = $user_model->field('password,mobile')->where($where)->find();
		//判断旧密码是否正确
		$db_password = $info['password'];
		$mobile      = $info['mobile'];
		if($db_password){
			$oldpassword = $this->_post('password','旧密码不能为空！');
			$password_md5 = password_md5_one($user_id, $oldpassword);
			if($db_password != $password_md5){
				$this->error('您输入的旧密码有误');
			}
		}

		//更新新密码
		$password_md5     = password_md5_one($user_id, $newpassword);
		$data['password'] = $password_md5;
		$user_model->where($where)->save($data);

		$this->success('设置密码成功！');
	}
	//忘记密码
	public function forget_password(){
		$mobile   = $this->_post('mobile','手机号不能为空！');
		$password = $this->_post('password','密码不能为空！');//经过一次MD5加密
		$smscode  = $this->_post('smscode','验证码不能为空！');

		//验证码判断
		$cache_smscode = S('API_SMSCODE_' . $mobile);
		if($cache_smscode != $smscode){
			$this->error('对不起，验证码不正确！');
		}
		//清空验证码缓存
		S('API_SMSCODE_' . $mobile, null);

		//获取用户信息
		$user_id = D('User')->get_mobile_user_id($mobile);
		if(!$user_id){
			$this->error('用户不存在！');
		}

		//再次MD5加密
		$data['password'] = password_md5_one($user_id, $password);
		$where['user_id']  = $user_id;
		D('User')->where($where)->save($data);

		$this->success('成功找回密码');

	}
	//验证用户密码
	public function check_password(){
		$user_id  = $this->user_id();
		$password = $this->_post('password', '密码不能为空！');

		//获取用户信息
		$where['user_id'] = $user_id;
		$info = D('User')->where($where)->find();

		$password_md5 = password_md5_one($user_id, $password);
		//判断密码
		if($info['password'] != $password_md5){
			$this->error('您输入密码有误！');
		}
		
		$this->success('密码验证成功！');
	}
	//更换手机号
	public function change_mobile(){
		$user_id    = $this->user_id();
		$new_mobile = $this->_post('new_mobile', '新手机号不能为空！');
		$smscode    = $this->_post('smscode', '验证码不能为空！');

		//手机号判断
		if(preg_match('/^1[34578][0-9]{9}$/', $new_mobile) == false){
			$this->error('对不起，手机号不正确！');
		}
		if(D('User')->mobile_exists($new_mobile)){
			$this->error('您输入的手机号已经注册过本平台，无法绑定！');
		}
		//获取用户信息
		$where['user_id'] = $user_id;
		$info = D('User')->where($where)->find();
		//获取原手机号
		$mobile      = $info['mobile'];
		//获取原密码
		$db_password = $info['password'];
		if($db_password){
			$password = $this->_post('password', '密码不能为空！');
			//验证密码
			$check_password = password_md5_one($user_id, $password);
			//验证输入密码是否正确
			if($check_password != $db_password){
				$this->error('对不起，您输入密码不对！');
			}
		}
		//验证码判断
		$cache_smscode = S('API_SMSCODE_' . $new_mobile);
		if($cache_smscode != $smscode){
			$this->error('对不起，验证码不正确！');
		}
		//清空验证码缓存
		S('API_SMSCODE_' . $mobile, null);
		
		$where['user_id'] = $user_id;
		$data['mobile']   = $new_mobile;
		D('User')->where($where)->save($data);
		
		$this->success('更换成功！');
	}
	//修改用户信息
	public function edit_info(){
		$user_id = $this->user_id();
		//真实姓名
		$realname = $this->_post('realname');
		if($realname){
			$data['realname'] = $realname;
		}
		//昵称
		$nickname = $this->_post('nickname');
		if($nickname){
			$data['nickname'] = $nickname;
		}
		//性别
		$sex = $this->_post('sex');
		if($sex){
			$data['sex'] = $sex;
		}
		//城市ID
		$city_id = $this->_post('city_id');
		if($city_id){
			//获取城市ID
			$data['city_id']     = $city_id;
			//获取省份ID
			$data['province_id'] = D('Area')->get_parent_id($city_id);
		}
		//地区ID
		$area_id = $this->_post('area_id');
		if($area_id){
			//获取城市ID
			$city_id = D('Area')->get_parent_id($area_id);
			//获取省份ID
			if($city_id){
				$province_id = D('Area')->get_parent_id($city_id);

				$data['province_id'] = $province_id;
				$data['city_id']     = $city_id;
				$data['area_id']     = $area_id;
			}
		}
		// var_dump($data);
		if($data){
			$where['user_id'] = $user_id;
			D('User')->where($where)->save($data);
			$user_info = D('User')->user_info($user_id);
			$this->success('修改成功！', $user_info);
		}else{
			$this->success('没有修改到任何信息！');
		}
	}
	//头像裁剪
	public function head_crop(){
		$user_id = $this->user_id();
		$file_id = $this->_post('file_id', '请选择图片！');
		$x1      = $this->_post('x1', '', 0);
		$y1      = $this->_post('y1', '', 0);
		$x2      = $this->_post('x2', 'x2不能为空');
		$y2      = $this->_post('y2', 'y2不能为空');
		$width   = $this->_post('width', 'width不能为空');
		$height  = $this->_post('height', 'height不能为空');
		
		$info = D('File')->get_file_info($file_id);
		if(!$info){
			$this->error('文件不存在！');
		}
		if(!in_array($info['ext'], array('jpg', 'png', 'bmp', 'jpeg'))){
			$this->error('[' . $info['ext'] . ']此图片文件格式无法裁剪！');
		}
		$crop_file_id = D('File')->crop($user_id, $file_id, $x1, $y1, $x2, $y2, $width, $height);
		if($crop_file_id){
			//更新头像
			D('User')->where(array('user_id' => $user_id))->save(array('head_id' => $crop_file_id));
			$data = D('File')->get_file_info($crop_file_id);
			$this->success('裁剪成功！', $data);
		}
		$this->error('裁剪失败！');
	}
	//获取用户信息
	public function get_user_info(){
		$user_id = $this->user_id();
		// if(!$user_id){
		// 	$this->error('获取不到用户ID！');
		// }
		//获取用户信息
		$user_info = D('User')->user_info($user_id);
		$user_info['token'] = D('User')->get_token($user_id);
		$this->success('获取成功！', $user_info);
	}
	//注册获取短信验证码
	public function get_smscode(){
		$mobile = $this->_get('mobile','手机号不能为空！');
		$type   = $this->_get('type');
		if(preg_match('/^1[34578][0-9]{9}$/',$mobile)==false){
			$this->error('对不起，手机号不正确！');
		}

		//判断是否可以发送
		$mobile_exists = D('User')->mobile_exists($mobile);
		//忘记密码判断
		if($type == 'forget_password' && $mobile_exists == false){
			$this->error('手机号不存在！');
		}
		//注册时判断是否注册过
		if($type == 'register' && $mobile_exists == true){
			$this->error('您的手机已经注册过，若忘记密码，请使用“找回密码”功能。');
		}
		//更换手机号
		if($type == 'update_mobile' && $mobile_exists == true){
			$this->error('手机号已存在，不能更换！');
		}
		
		//短信发送时间限制
		$sms_time   = S('API_SMSCODE_TIME'.$mobile);
		$sms_time   = $sms_time ? $sms_time : 0;
		$limit_time = 60;
		if((time() - $sms_time) <= $limit_time){
			$this->error('对不起，1分钟内不能重复获取短信验证码，请过后再试！');
		}

		//判断发送次数，按天
		$sms_num  = S('API_SMSCODE_NUM_'.$mobile);
		$sms_num  = $sms_num ? $sms_num : 0;
		if($sms_num >= 10){
			$this->error('您发送短信次数过多！');
		}

		//判断发送次数，30分钟内只能发送3条短信
		$sms_30time  = S('API_SMSCODE_30TIME'.$mobile);
		$sms_30time  = $sms_30time ? $sms_30time : 0;
		if((time() - $sms_30time) < 30 * 60 && $sms_num >= 3){
			$this->error('对不起，30分钟内只能发送3条短信，请过后再试！');
		}

		//缓存验证码
		$smscode = S('API_SMSCODE_' . $mobile);
		//生成验证码
		$smscode = $smscode ? $smscode : \Org\Util\String::randString(6,1);
		//短信内容
		$smscode_tpl = Conf('smscode_tpl', 'sms');
		$smscode_tpl = str_replace(
			array('#code#', '#signature#'),
			array($smscode, Conf('signature','sms')),
			$smscode_tpl
		);
		$content = $smscode_tpl ? $smscode_tpl : '您的短信验证码为' . $smscode;

		//发送短信
		import("Sms",'Public/Class/suncco/');
		$sms  = new \Sms();
		//设置验证码
		$sms->smscode = $smscode;
		$info = $sms->send($mobile, $content);
		if($info['status'] == 200){
			//缓存验证码10分钟
			S('API_SMSCODE_' . $mobile, $smscode,600);
			//保存发送次数，保存半天
			S('API_SMSCODE_NUM_' . $mobile, $sms_num + 1, 12 * 60 * 60);
			//保存当前短信发送时间
			S('API_SMSCODE_TIME' . $mobile, time());
			//保存当前短信发送时间，每30分钟一次
			if(!$sms_30time){
				S('API_SMSCODE_30TIME' . $mobile, time(), 30 * 60);
			}
			$this->success('发送成功，请注意查收！');
		}else{
			$this->error('短信发送失败->' . $info['info']);
		}
	}
	//获取语音验证码
	public function get_voice_code(){
		$mobile = $this->_get('mobile','手机号不能为空！');
		$type   = $this->_get('type');
		if(preg_match('/^1[34578][0-9]{9}$/',$mobile)==false){
			$this->error('对不起，手机号不正确！');
		}
		//判断是否可以发送
		$mobile_exists = D('User')->mobile_exists($mobile);
		//忘记密码判断
		if($type == 'forget_password' && $mobile_exists == false){
			$this->error('手机号不存在！');
		}
		//注册时判断是否注册过
		if($type == 'register' && $mobile_exists == true){
			$this->error('您的手机已经注册过，若忘记密码，请在登录页面使用“找回密码”功能。');
		}
		//更换手机号
		if($type == 'update_mobile' && $mobile_exists == true){
			$this->error('手机号已存在，不能更换！');
		}
		//短信发送时间限制
		$sms_time   = S('API_VOICECODE_TIME' . $mobile);
		$sms_time   = $sms_time ? $sms_time : 0;
		$limit_time = 60;
		if((time() - $sms_time) <= $limit_time){
			$this->error('对不起，1分钟内不能重复获取短信验证码，请过后再试！');
		}

		//判断发送次数，按天
		$sms_num  = S('API_VOICECODE_NUM_' . $mobile);
		$sms_num  = $sms_num ? $sms_num : 0;
		if($sms_num >= 10){
			$this->error('您发送短信次数过多！');
		}

		//判断发送次数，30分钟内只能发送3条短信
		$sms_30time  = S('API_VOICECODE_30TIME' . $mobile);
		$sms_30time  = $sms_30time ? $sms_30time : 0;
		if((time() - $sms_30time) < 30 * 60 && $sms_num >= 3){
			$this->error('对不起，30分钟内只能发送3条短信，请过后再试！');
		}
		//缓存验证码
		$smscode = S('API_SMSCODE_' . $mobile);
		//生成验证码
		$smscode = $smscode ? $smscode : \Org\Util\String::randString(6,1);
		//发送语音
		import("Sms",'Public/Class/suncco/');
		$sms  = new \Sms();
		$info = $sms->yunpian_voice_send($mobile, $smscode);
		if($info['status'] == 200){
			//缓存验证码30分钟
			S('API_SMSCODE_' . $mobile, $smscode, 1800);
			//保存发送次数，保存半天
			S('API_VOICECODE_NUM_' . $mobile, $sms_num + 1, 12 * 60 * 60);
			//保存当前短信发送时间
			S('API_VOICECODE_TIME' . $mobile, time());
			//保存当前短信发送时间，每30分钟一次
			if(!$sms_30time){
				S('API_VOICECODE_30TIME' . $mobile, time(), 30 * 60);
			}
			$this->success('发送成功，请注意查收！');
		}else{
			$this->error('发送失败->' . $info['info']);
		}
	}
	//检查验证码是否正确
	public function check_smscode(){
		$mobile  = $this->_post('mobile','手机号不能为空！');
		$smscode = $this->_post('smscode','验证码不能为空！');
		//验证码判断
		$cache_smscode = S('API_SMSCODE_'.$mobile);
		if($cache_smscode != $smscode){
			$this->error('对不起，验证码不正确！');
		}

		$this->success('验证码正确！');
	}


	//第三方登录
	public function sso_login(){
		$sso_type = $this->_post('sso_type', '第三方类型不能为空！');
		$open_id  = $this->_post('open_id', '第三方用户唯一标识不能为空！');

		//获取绑定用户ID
		$user_id = D('User')->get_sso_user_id($open_id, $sso_type);
		if($user_id){
			$info  = D('User')->user_info($user_id);
			//判断是否禁用
			if($info['status'] == 0){
				$this->error('您的账号被禁用，请联系相关人员！');
			}
			//获取用户登录TOKEN
			$token = D('User')->make_token($user_id);
			$info['token'] = $token;
			$this->success('登录成功！', $info);
		}else{
			$this->error('您的第三方账号尚未绑定！', '', 410);
		}
	}
	//第三方登录注册
	public function sso_register(){
		$sso_type = $this->_post('sso_type', '第三方类型不能为空！');
		$open_id  = $this->_post('open_id', '第三方用户唯一标识不能为空！');
		$nickname = $this->_post('nickname', '');//昵称
		$realname = $this->_post('realname', '');//真实姓名
		$email    = $this->_post('email', '');//E-mail
		$sex      = $this->_post('sex', '');//性别
		$city_id  = $this->city_id();//城市ID
		$head_url = $this->_post('head_url', '');//头像URL
		$head_url = urldecode($head_url);

		//获取绑定用户ID
		$user_id = D('User')->get_sso_user_id($open_id, $sso_type);
		if($user_id){
			$this->error('您已绑定过了！');
		}

		//生成用户ID
		$user_id = D('User')->generate_user_id();
		$data['user_id'] = $user_id;
		//更新用户信息
		if($nickname){
			$data['nickname'] = $nickname;
		}
		if($realname){
			$data['realname'] = $realname;
		}
		if($email){
			$data['email'] = $email;
		}
		if($sex){
			$data['sex'] = $sex;
		}
		if($head_url){
			$data['head_id'] = D('File')->down_remote_img($head_url, 'head', $user_id);
		}
		if(!$user_id){
			$this->error('绑定失败，请稍候再试！！！');
		}
		//省份城市ID
		if($city_id){
			$data['city_id']     = $city_id;
			$data['province_id'] = D('Area')->get_parent_id($city_id);
		}
		//创建用户
		D('User')->add($data);
		unset($data);
		if(!$user_id){
			$this->error('绑定失败，请稍候再试！！！');
		}
		//创建第三方账号
		$data['user_id']     = $user_id;
		$data['open_id']     = $open_id;
		$data['sso_type']    = $sso_type;
		$data['nickname']    = $nickname ? $nickname : '';
		$data['create_time'] = time();
		D('UserSso')->add($data);
		//获取注册用户信息
		$info = D('User')->user_info($user_id);
		if(!$info){
			$this->error('绑定失败，请稍候再试！');
		}
		$info['token'] = D('User')->make_token($user_id);
		$this->success('绑定成功！', $info);
	}
	//第三方账号绑定
	public function sso_bind(){
		$user_id  = $this->user_id();
		$sso_type = $this->_post('sso_type','第三方类型不能为空！');
		$open_id  = $this->_post('open_id','第三方用户唯一标识不能为空！');
		$nickname = $this->_post('nickname');//昵称

		//判断用户是否有绑定
		$is_bind = D('User')->get_sso_user_id($open_id, $sso_type);
		if($is_bind){
			$this->error('此账号已被绑定过了！');
		}

		//创建第三方账号
		$data['user_id']     = $user_id;
		$data['sso_type']    = $sso_type;
		$data['open_id']     = $open_id;
		$data['nickname']    = $nickname ? $nickname : '';
		$data['create_time'] = time();
		D('UserSso')->add($data);
		$this->success('绑定成功！');
	}
	//解除第三方绑定
	public function sso_unbind(){
		$user_id  = $this->user_id();
		$sso_type = $this->_post('sso_type','第三方类型不能为空！');

		$where['user_id'] = $user_id;
		$user_info = D('User')->where($where)->find();
		if(!$user_info['mobile']){
			$this->error('您为第三方登录账号，无法取消绑定！');
		}
		//判断用户是否有绑定
		if(D('User')->is_bind($user_id, $sso_type)){
			$where['user_id']  = $user_id;
			$where['sso_type'] = $sso_type;
			D('UserSso')->where($where)->delete();
			$this->success('解除绑定成功！');
		}else{
			$this->error('您尚未绑定，不能解除绑定！');
		}
	}
	//积分列表接口
	public function score_list(){
		$user_id = $this->user_id();
		//分页参数
		$page      = $this->_get('page', '', 1);
		$pagesize  = $this->_get('pagesize', '', 10);
		$first_row = $pagesize * ($page - 1);

		$where['user_id'] = $user_id;
		$count = D('ScoreLogs')->where($where)->count();
		$list  = D('ScoreLogs')->where($where)->order('id desc')->limit($first_row . ',' . $pagesize)->select();
		$score_config = C('score_config');
		foreach ($list as $rs) {
			$rs['title'] = $score_config[$rs['role']]['title'];
			$rs['date']  = date('Y-m-d', $rs['create_time']);
			$rs['dtim']  = date('Y-m-d H:i:s', $rs['create_time']);
			$rs['score'] = $rs['score'] > 0 ? '+' . $rs['score'] : $rs['score'];
			$new_list[]  = $rs;
		}
		
		$data['list']        = $new_list ? $new_list : array();
		$data['page_info']   = $this->page_info($count, $pagesize);
		$data['total_score'] = D('User')->get_user_score($user_id);

		if($list){
			$this->success('获取数据成功！', $data);
		}else{
			$this->success('找不到相关数据!', $data);
		}
	}
}